package com.byt.user.activity;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.byt.base.activity.BaseActivity;
import com.byt.base.preference.SharePerUtils;
import com.byt.base.utils.MD5Security;
import com.byt.common.BaseColor;
import com.byt.common.Constants;
import com.byt.common.bean.VersionInfo;
import com.byt.common.util.FormatUtil;
import com.byt.common.util.UpdateVersionUtil;
import com.byt.common.view.AuthenticaDialog;
import com.byt.netapi.boby.FormBodys;
import com.byt.user.R;
import com.byt.user.bean.LoginBean;
import com.byt.user.databinding.ActivityLoginBinding;
import com.byt.user.viewmodel.LoginViewModel;
import com.igexin.sdk.PushManager;

import java.util.HashMap;

/**
 * 类名称：  LoginActivity
 * 类描述：  登录界面
 */
public class LoginActivity extends BaseActivity<ActivityLoginBinding, LoginViewModel> implements LoginViewModel.LoginView {

    private long nowTime;
    private int mCount;
    private long mPreClickTime;
    private static final int SWITCH_VERSION_CLK_NUM = 5;

    @Override
    protected void onRetryBtnClick() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected LoginViewModel getViewModel() {
        return new LoginViewModel(new HashMap<>());
    }

    @Override
    public int getBindingVariable() {
        return 0;
    }

    private String userName;
    private String mCid;
    private boolean isExit = false;


    @Override
    protected void initParameters() {
        super.initParameters();
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        SetStatusBarColor(BaseColor.color_white);
        userName = SharePerUtils.getInstance().getString(Constants.EXPERTS_NAME);
        showContent();
        if (userName != null) {
            dataBinding.edPhone.setText(userName);
            dataBinding.edPhone.setSelection(userName.length());
            dataBinding.edPassword.setText("");
        }
//        dataBinding.tvLogin.setOnClickListener(this);
//        dataBinding.llRegis.setOnClickListener(this);
//        dataBinding.tvFindPassword.setOnClickListener(this);
//        dataBinding.ivBg.setOnClickListener(this);
//        dataBinding.tvLastLogin.setOnClickListener(this);
//        dataBinding.mCheckSwithcButton1.setOnClickListener(this);
//        dataBinding.tvUserAgreement.setOnClickListener(this);
//        dataBinding.tvPrivacyPolicy.setOnClickListener(this);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (null != this.getCurrentFocus()) {
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }


    @Override
    public void onUpdateApp(VersionInfo versionInfo) {
        UpdateVersionUtil.showUpdateDialog(this, versionInfo, "xdoctor.apk");
    }


    @Override
    public void loginSuccess(LoginBean mBean) {
        stopProgressDialog();
        if (mBean != null) {
            if (mBean.getExpert().complete == 0) {
                // 跳完善资料
                openActivity(PerfectInfoActivity.class);
            } else if (mBean.getExpert().complete == 1) {
                // 认证弹窗
                AuthenticaDialog dialog = new AuthenticaDialog.Builder(this)
                        .setOnListener(new AuthenticaDialog.OnAuthenticaListener() {
                            @Override
                            public void onGoAuth() {
//                                openActivity(AuthenticaInfoActivity.class);
                            }

                            @Override
                            public void onCancelAuth() {
//                                openActivity(MainActivity.class);
//                                finish();
                            }
                        }).build();
                dialog.show();
            } else {
//                openActivity(MainActivity.class);
                finish();
            }
        }
    }

    @Override
    public void onCode(String code, String msg) {
        stopProgressDialog();
    }


    private void postLogin() {
        if (TextUtils.isEmpty(dataBinding.edPhone.getText().toString())) {
            showShortToast("请输入手机号");
        } else if (!FormatUtil.isMobileNO(dataBinding.edPhone.getText().toString())) {
            showShortToast("请输入正确的手机号");
        } else if (TextUtils.isEmpty(dataBinding.edPassword.getText().toString())) {
            showShortToast("请输入密码");
        } else if (dataBinding.edPassword.getText().toString().length() < 6) {
            showShortToast("密码长度6位以上");
        } else if (dataBinding.edPassword.getText().toString().length() > 20) {
            showShortToast("输入的密码不能超过20位");
        } else if (!FormatUtil.isPassword(dataBinding.edPassword.getText().toString())) {
            showShortToast("请输入正确密码");
        } else if (!FormatUtil.isLetterOrNum(dataBinding.edPassword.getText().toString())) {
            showShortToast("密码必须包含字母和数字");
        } else if (dataBinding.edPhone.getText().toString().equals(dataBinding.edPassword.getText().toString())) {
            showShortToast("账号与密码不能相同");
        } else {
            try {
                mCid = PushManager.getInstance().getClientid(this);
            } catch (Exception e) {
                mCid = "";
            }
            FormBodys formBody = new FormBodys.Builder()
                    .add("mobile", dataBinding.edPhone.getText().toString())
                    .add("password", MD5Security.getMd5_32(dataBinding.edPassword.getText().toString()))
                    .add("client_id", mCid)
                    .build();
            startProgressDialog("Loading...");
            viewModel.loginUser(formBody);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //判断用户是否点击了“返回键”
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    private void exit() {
        if (!isExit) {
            isExit = true;
            showShortToast("再按一次退出程序");
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
//            PlayService service = GlobarApp.getPlayService();
//            if (service != null) {
//                service.quit();
//            }
            finish();
            System.exit(0);
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

    public class LoginHandler {
        public void login(View view) {
            nowTime = System.currentTimeMillis();
            if (mCount >= SWITCH_VERSION_CLK_NUM && nowTime - mPreClickTime < 1000) {
                openActivity(MilitaryForbidAreaActivity.class);
            } else {
                postLogin();
            }
        }

        public void register(View view) {
            openActivity(RegisterActivity.class);
        }

        public void ivbgClick(View view) {
            nowTime = System.currentTimeMillis();
            if (nowTime - mPreClickTime < 1000) {
                mCount++;
            } else {
                mCount = 1;
            }
            mPreClickTime = nowTime;
        }

        public void lastLogin(View view) {
            openActivity(LastLoginActivity.class);
        }

        public void checkSwithcButton(View view) {
            if (dataBinding.mCheckSwithcButton1.isSelected()) {
                dataBinding.mCheckSwithcButton1.setSelected(false);
            } else {
                dataBinding.mCheckSwithcButton1.setSelected(true);
            }
            if (dataBinding.mCheckSwithcButton1.isSelected()) {
                dataBinding.edPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            } else {
                dataBinding.edPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
            dataBinding.edPassword.setSelection(dataBinding.edPassword.length());
        }

        public void privacyPolicy(View view) {
            Bundle mPathBundle = new Bundle();
            mPathBundle.putString(CommonPathViewActivity.INP_URL_PATH, "http://www.xmxbaby.com/xmh5/h5/activity/notice/index.html");
            mPathBundle.putString(CommonPathViewActivity.INP_TITLE, "隐私政策");
            openActivity(CommonPathViewActivity.class, mPathBundle);
        }

        public void userAgreement(View view) {
            Bundle mRichBundle = new Bundle();
            mRichBundle.putInt(CommonRichTextActivity.RICH_TEXT_TYPE, 0);
            openActivity(CommonRichTextActivity.class, mRichBundle);
        }

        public void findPassword(View view) {
            Bundle bundle = new Bundle();
            bundle.putInt(FindPasswordActivity.INP_PWDTYPE, 1);
            openActivity(FindPasswordActivity.class, bundle);
        }

    }


}